/*
 * Copyright 2020 lcnap
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package pers.lcnap.simplerpc.rpc;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pers.lcnap.simplerpc.rpc.handler.RpcCallChannelHandler;
import pers.lcnap.simplerpc.rpc.handler.RpcRequestQueueChannelHandler;
import pers.lcnap.simplerpc.rpc.handler.codec.ByteToRpcResponseDecoder;
import pers.lcnap.simplerpc.rpc.handler.codec.RpcRequestToByteEncoder;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * Netty Client端，建立通道，用于发起请求。绑定 本地请求 队列。
 */
public class NettyClient {

    private final Logger logger = LoggerFactory.getLogger(NettyClient.class);

    private final ConcurrentLinkedQueue<RpcRequestEvent> queue;

    private EventLoopGroup workerGroup;

    private Bootstrap bootstrap;

    private List<Channel> channels;

    private String host = "127.0.0.1";

    private int port = 8080;

    private int channelNum = Runtime.getRuntime().availableProcessors() / 2;


    public NettyClient(String host, int port) {
        this();
        this.host = host;
        this.port = port;
    }

    public NettyClient() {
        workerGroup = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        queue = new ConcurrentLinkedQueue<>();
        channels = new ArrayList<>();
        intBootstrap();

    }


    private void intBootstrap() {
        bootstrap.group(workerGroup);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline()
                        .addLast(new ByteToRpcResponseDecoder())
                        .addLast(new RpcRequestToByteEncoder())
                        .addLast(new RpcRequestQueueChannelHandler(queue))
                        .addLast(new RpcCallChannelHandler());
            }
        });
    }

    private void doConnect() throws InterruptedException {
        ChannelFuture connect = bootstrap.connect(host, port).sync();
        Channel channel = connect.channel();
        channels.add(channel);
    }


    public void connect()   {
        try {
            for (int i = 0; i < channelNum; i++) {
                doConnect();
                logger.info("channel {} connected.", i + 1);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    /**
     * 发送{@link RpcRequestEvent} 到请求队列。
     *
     * @param event
     */
    public void sendRequestEvent(RpcRequestEvent event) {
        queue.add(event);
    }

    public void shutdown() {
        channels.forEach(ChannelOutboundInvoker::close);
        workerGroup.shutdownGracefully();
    }
}
